package week01.challenge;

import sun.misc.Resource;
import sun.misc.URLClassPath;

import java.io.IOException;
import java.net.URL;

/**
 * @author edward
 * @since 2021-06-26
 */
public class XlassLoader extends ClassLoader {

    private final URLClassPath ucp;
    XlassLoader(URL[] urls) {
        ucp = new URLClassPath(urls);
    }

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        if (name == null) {
            throw new IllegalArgumentException("Name must not be empty");
        }
        String path = name.replace(".", "/").concat(".xlass");
        Resource resource = ucp.getResource(path);
        byte[] src;
        try {
            src = resource.getBytes();
            for (int i = 0; i < src.length; i++) {
                src[i] = (byte) (255 - src[i]);
            }
        } catch (IOException e) {
            throw new ClassNotFoundException(path + ".xlass NOT FOUND", e);
        }
        return defineClass(name, src, 0, src.length);
    }

    public void addURL(URL... urls) {
        for (URL url : urls) {
            ucp.addURL(url);
        }
    }
}
